package com.hongyi.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hongyi.common.excel.utils.ExcelUtil;
import com.hongyi.common.framework.constant.UserConstans;
import com.hongyi.common.framework.domain.JsonResult;
import com.hongyi.common.framework.utils.ServletUtils;
import com.hongyi.common.framework.utils.bean.MapstructUtils;
import com.hongyi.common.framework.validate.EditGroup;
import com.hongyi.common.framework.validate.StatusGroup;
import com.hongyi.common.log.annotation.Log;
import com.hongyi.common.log.enums.BusinessType;
import com.hongyi.common.mybatis.page.PageData;
import com.hongyi.common.mybatis.page.PageQuery;
import com.hongyi.common.web.controller.BaseController;
import com.hongyi.system.domain.SysRole;
import com.hongyi.system.domain.dto.SysRoleDto;
import com.hongyi.system.domain.vo.SysRoleVo;
import com.hongyi.system.domain.vo.SysUserVo;
import com.hongyi.system.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;


/**
 * 系统角色信息
 *
 * @author DingHao
 */
@ApiSort(value = 3)
@Api(tags = "角色信息接口")
@Validated
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 获取角色分页数据
     *
     * @param sysRoleDto 角色对象
     * @param pageQuery  分页查询条件
     * @return 分页角色数据集合信息
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取角色分页数据")
    @ApiImplicitParam(name = "role", value = "角色对象", paramType = "query", dataTypeClass = SysRole.class)
    @SaCheckPermission("system:role:list")
    @GetMapping(value = "/list")
    public PageData<SysRoleVo> list(SysRoleDto sysRoleDto, PageQuery pageQuery) {
        return sysRoleService.selectRoleList(sysRoleDto, pageQuery);
    }

    /**
     * 导出角色列表"
     *
     * @param sysRoleDto     角色
     * @param response 返回
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "角色导出(流形式)")
    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @SaCheckPermission("system:role:export")
    @PostMapping(value = "/exportByStream", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void responseStream(SysRoleDto sysRoleDto, HttpServletResponse response) {
        List<SysRoleVo> sysRoleVos = sysRoleService.selectRoleList(sysRoleDto);
        ExcelUtil.exportExcel(sysRoleVos, "用户数据", SysRoleVo.class, response);

    }

    /**
     * 根据角色编号获取详细信息
     *
     * @param roleId 角色id
     * @return 角色对象
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "根据角色编号获取详情")
    @ApiImplicitParam(name = "roleId", value = "角色数组", dataTypeClass = Long.class, required = true)
    @SaCheckPermission("system:role:query")
    @GetMapping(value = "/{roleId}")
    public JsonResult<SysRoleVo> getInfo(@PathVariable Long roleId) {
        return JsonResult.ok(sysRoleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     *
     * @param role 角色对象
     * @return 结果
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "新增角色")
    @SaCheckPermission("system:role:add")
    @Log(title = "新增角色", businessType = BusinessType.INSERT)
    @PostMapping
    public JsonResult<Void> add(@Validated @RequestBody SysRole role) {
        if (UserConstans.NOT_UNIQUE.equals(sysRoleService.checkRoleNameUnique(role))) {
            return JsonResult.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstans.NOT_UNIQUE.equals(sysRoleService.checkRoleKeyUnique(role))) {
            return JsonResult.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        return toResult(sysRoleService.insertRole(role));
    }

    /**
     * 修改角色
     *
     * @param sysRoleDto 角色对象
     * @return 结果
     */
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "修改角色")
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public JsonResult<String> edit(@Validated(EditGroup.class) @RequestBody SysRoleDto sysRoleDto) {
        SysRole sysRole = MapstructUtils.convert(sysRoleDto, SysRole.class);
        sysRoleService.checkRoleAllowed(Objects.requireNonNull(sysRole));
        if (UserConstans.NOT_UNIQUE.equals(sysRoleService.checkRoleNameUnique(sysRole))) {
            return JsonResult.fail("新增角色'" + sysRole.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstans.NOT_UNIQUE.equals(sysRoleService.checkRoleKeyUnique(sysRole))) {
            return JsonResult.fail("新增角色'" + sysRole.getRoleName() + "'失败，角色权限已存在");
        }
        if (sysRoleService.updateRole(sysRole) > 0) {
            sysRoleService.cleanOnlineUserByRole(sysRole.getRoleId());
            return JsonResult.ok();
        }
        return JsonResult.fail("修改角色'" + sysRole.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     *
     * @param role 角色对象
     * @return 结果
     */
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "角色数据权限保存")
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public JsonResult<Void> dataScope(@RequestBody SysRole role) {
        this.sysRoleService.checkRoleAllowed(role);
        return toResult(sysRoleService.authDataScope(role));
    }

    /**
     * 角色状态修改
     *
     * @param sysRoleDto 角色对象
     * @return 结果
     */
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "角色状态修改")
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public JsonResult<Void> changeStatus(@Validated(StatusGroup.class) @RequestBody SysRoleDto sysRoleDto) {
        return toResult(sysRoleService.updateRoleStatus(sysRoleDto));
    }

    /**
     * 批量删除角色
     *
     * @param roleIds 角色ID数组
     * @return 结果
     */
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "批量删除角色")
    @ApiImplicitParam(name = "roleIds", value = "角色ID数组", dataTypeClass = Long.class, allowMultiple = true, required = true)
    @SaCheckPermission("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public JsonResult<Void> remove(@PathVariable Long[] roleIds) {
        return toResult(sysRoleService.deleteRoleByIds(roleIds));
    }


}
